#include "music.h"
#include "ui_music.h"


music::music(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::music)
{
    ui->setupUi(this);
    //隐藏标题栏
    this->setWindowFlag(Qt::FramelessWindowHint);

    manager = new QNetworkAccessManager(this);
    connect(manager, SIGNAL(finished(QNetworkReply*)),
            this, SLOT(replyFinished(QNetworkReply*)));

    pModel = new QStandardItemModel(10,4,ui->tableView);
    //设置数据模型的表头
    QStringList list = QStringList()<<"名字"<<"专辑"<<"歌手"<<"时长";
    pModel->setHorizontalHeaderLabels(list);//设置数据的表头

    ui->tableView->setModel(pModel);
    for (int i=0;i<4;i++) {
        ui->tableView->setColumnWidth(i,175);
    }

    playlist = new QMediaPlaylist;
    player = new QMediaPlayer;
    player->setPlaylist(playlist);

    connect(player, SIGNAL(durationChanged(qint64 )),
            this, SLOT(durationchanged(qint64 )));
    connect(player,SIGNAL(positionChanged(qint64 )),
            this,SLOT( positionchanged(qint64 )));
    connect(ui->pushButton_begin, &QPushButton::clicked, this, &music::togglePlayPause);
    connect(ui->horizontalSlider_2, &QSlider::valueChanged, this,
            &music::volumechange);
    icon1 = QIcon("d:/image/stop.bmp");
    icon2 = QIcon("d:/image/begin.bmp");
    icon3=QIcon("d:/image/volume.png");
    icon4=QIcon("d:/image/volumeclose.png");
    player->setVolume(50);
    ui->horizontalSlider_2->setRange(0,100);
    ui->horizontalSlider_2->setValue(50);
    ui->pushButton_2->setIcon(icon3);


}

music::~music()
{
    delete ui;
}

void music::volumechange(int value)
{
    player->setVolume(value);
}

void music::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.drawPixmap(0,0,width(),height(),QPixmap("d:/image/1.png"));
}
//pushbutton->搜索
void music::on_pushButton_clicked()
{
    manager->get(QNetworkRequest(QUrl(QString("http://music.163.com/api/search/get/web?csrf_token=hlpretag=&hlposttag=&s=%1&type=1&offset=0&total=true&limit=10").arg(ui->lineEdit->text()))));
}
//访问网络服务器
void music::replyFinished(QNetworkReply *reply)
{
    qDebug()<<reply->attribute(QNetworkRequest::HttpStatusCodeAttribute)<<endl;
    if(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute) == 200)
        {
            qDebug()<<"音乐播放"<<"访问服务器成功"<<endl;
//            qDebug()<<QString(reply->readAll())<<endl;
        parejson(reply->readAll());
    }
}

void music::parejson(QByteArray byteArray)
{
    playlist->clear();//clear playlist

    QJsonDocument doc=QJsonDocument::fromJson(byteArray);
    if(doc.isObject()==true){
        qDebug()<<"该文档是一个对象"<<endl;
        QJsonObject obj1=doc.object();
        if(obj1.contains("result")==false){
            qDebug()<<"错误的JSON对象"<<endl;
            return;
        }
        QJsonValue var=obj1.value("result");
        QJsonObject resultObj =var.toObject();
        if(resultObj.contains("songs")==false){
            qDebug()<<"JSON对象没有歌曲"<<endl;
            return;
        }
        var=resultObj.value("songs");
        if(var.isArray()){
             QJsonArray songsArr=var.toArray();
             qDebug()<<"搜索到"<<songsArr.size()<<"首歌曲"<<endl;
             for (int i=0;i<songsArr.size();i++) {
                 QJsonObject songObj = songsArr[i].toObject();//把下标为i的元素转为对象
                 if(songObj.contains("id"))
                 {
                     QJsonValue varID = songObj.value("id");//获取关键字为id的元素的值
                     id = varID.toInt();//把值转为整数

                 }
                 if(songObj.contains("name"))
                 {
                     QJsonValue varName = songObj.value("name");
                     songName = varName.toString();
                 }
                 if(songObj.contains("album"))//是否包含专辑
                 {
                     QJsonValue varAlbum = songObj.value("album");//得到专辑关键字的值
                     if(varAlbum.isObject())
                     {
                         QJsonObject albumObj = varAlbum.toObject();//把专辑的值转为对象
                         if(albumObj.contains("name"))
                         {
                             QJsonValue varAlbumName =  albumObj.value("name");
                             albumName = varAlbumName.toString();//得到专辑名
                         }
                     }
                 }
                 if(songObj.contains("artists"))//是否包含作者关键字
                 {
                     QJsonValue varArtists = songObj.value("artists");
                     if(varArtists.isArray())//作者的值是否为数组
                     {
                         QJsonArray arrArtists = varArtists.toArray();
                         for (int i = 0; i < arrArtists.size(); ++i) {//遍历作者数组
                             if(arrArtists[i].isObject())
                             {
                                 QJsonObject artistsObj = arrArtists[i].toObject();
                                 if(artistsObj.contains("name"))
                                 {
                                     QJsonValue varArtistsName = artistsObj.value("name");
                                     singerName+= varArtistsName.toString();//把名字加入到字符串中
                                     singerName+=" ";//中间留一个空格
                                 }
                             }
                         }
                     }
                 }
                 if(songObj.contains("duration"))
                 {
                     QJsonValue varDuration = songObj.value("duration");//获取关键字为duration的元素的值
                     int duration1=varDuration.toInt()/1000;
                     fen = duration1/60;
                     miao=duration1 % 60;

                 }
                 qDebug()<<id<<" "<<songName<<" "<<albumName<<" "<<singerName<<" "<<duration<<endl;
                 playlist->addMedia(QUrl(QString("http://music.163.com/song/media/outer/url?id=%1.mp3").arg(id)));
                 QStandardItem *item = new QStandardItem(songName);//歌名
                 pModel->setItem(i, 0, item);
                 item = new QStandardItem(singerName);
                 pModel->setItem(i, 1, item);
                 item = new QStandardItem(albumName);
                 pModel->setItem(i, 2, item);
                 item = new QStandardItem(QString("%1:%1").arg(fen).arg(miao));
                 pModel->setItem(i, 3, item);
                 singerName = "";//清空歌手名
                 playlist->setCurrentIndex(0);

             }
        }
    }
}



void music::on_tableView_doubleClicked(const QModelIndex &index)
{
    qDebug()<<index.row()<<endl;
    playlist->setCurrentIndex(index.row());
    player->play();
    isPlaying=true;
    ui->pushButton_begin->setIcon(icon2);

}

void music::on_horizontalSlider_sliderReleased()
{
    qint64 var=ui->horizontalSlider->value();
    player->setPosition(var);
}

void music::positionchanged(qint64 position)
{
    ui->horizontalSlider->setValue(position);
     qDebug()<<position<<endl;
}

void music::durationchanged(qint64 duration)
{
    qDebug()<<"总时长"<<duration<<"ms"<<endl;
    ui->horizontalSlider->setRange(0,duration);
}

void music::on_pushButton_close_clicked()
{
    close();
}
void music::togglePlayPause() {
        if (isPlaying) {
            player->pause();
            ui->pushButton_begin->setIcon(icon2);
//
        } else {
            player->play();
            ui->pushButton_begin->setIcon(icon1);

        }
        isPlaying = !isPlaying;
    }

void music::on_pushButton_prev_clicked()
{
    playlist->previous();
    player->play();
}

void music::on_pushButton_next_clicked()
{
    playlist->next();
    player->play();
}

void music::on_pushButton_begin_clicked()
{

}

void music::on_pushButton_2_clicked()
{


    if(voice!=true){
        ui->pushButton_2->setIcon(icon4);
        player->setVolume(0);
        ui->horizontalSlider_2->setValue(0);

    }else{
        ui->pushButton_2->setIcon(icon3);
        player->setVolume(50);
        ui->horizontalSlider_2->setValue(50);
    }
    voice=!voice;
}


